##使用curve_fit
import numpy as np
import matplotlib.pyplot as plt
from numpy import mean
from scipy.optimize import curve_fit, leastsq
import math
from sympy import *

def func(x, k,i):
    return 28.1*(1+(i-1)*np.exp(-1*k*10))*k*(i-1)*np.exp(-1*k*x)/((1+((i-1)*np.exp(-1*k*x)))**2)#a * np.sqrt(x) * (b * np.square(x) + c)
# 定义x、y散点坐标
x = [1,2,3,4,5,6,7,8,9,10]
x = np.array(x)
num = [1.0,1.2,1.6,2.6,2.7,3.6,3.7,4.2,3.8,3.7]
y = np.array(num)
x20=np.array([10,11,12,13,14,15,16,17,18,19,20])

# 非线性最小二乘法拟合
popt, pcov = curve_fit(func, x, y,maxfev=10000000)
# 获取popt里面是拟合系数
print(popt)
k = popt[0]
i = popt[1]
yvals = func(x, k, i)  # 拟合y值
print('popt:', popt)
print('系数k:', k)
print('系数i:', i)
print('系数pcov:', pcov)
print('系数yvals:', yvals)
y20=func(x20, k,i)
print('预计未来十年产量',y20)
# 绘图
plot1 = plt.plot(x, y, 's', label='original data')
plot2 = plt.plot(x, yvals, 'r', label='Fitting function')
plot3 = plt.plot(x20, y20, 'b', label='forecast')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=4)  # 指定legend的位置右下角
plt.title('Mining problem function fitting')
plt.show()